System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

71% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Day 10: Software Infrastructure
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design an API Gateway
Image

Here is the step-by-step system design for an API Gateway.

1. Problem Definition and Scope

We are designing a scalable API Gateway. This is a server that acts as the single entry point for all external traffic (mobile apps, web browsers, partners) entering our microservices architecture.

Instead of clients calling fifty different services directly, they call the Gateway, which routes the request to the right place.

Main User Groups:

  • External Clients: End-users or apps sending requests to access data.

  • Internal Developers: Engineers who configure routes, rate limits, and security policies.

Scope:

We will focus on the Data Plane (handling live traffic) and the Control Plane (managing configuration).

  • In Scope: Request routing, Authentication (AuthN), Rate limiting, SSL termination, and Service discovery.

  • Out of Scope: The internal logic of the microservices themselves, billing systems, or heavy payload transformation (e.g., SOAP to REST).

Image

2. Clarify functional requirements

Must Have:

  • Request Routing: Forward requests based on the URL path (e.g., /users User Service) to the correct backend service.

  • Authentication: Verify user identity (e.g., validate JWT tokens) centrally so individual services don't have to.

  • Rate Limiting: Limit the number of requests a client can make in a specific time window to prevent abuse.

  • Service Discovery: Automatically detect the IP addresses of dynamic backend services.

  • SSL Termination: Handle HTTPS decryption at the gateway to offload CPU work from backend services.

Nice to Have:

  • Circuit Breaking: Stop sending traffic to a failing service to prevent cascading failures.

  • Response Caching: Cache frequent responses (like a list of countries) to reduce load on backends.

  • Protocol Translation: Accept HTTP/1.1 from clients but speak gRPC or HTTP/2 to backends.

Image

3. Clarify non-functional requirements

  • Target Users: The system handles 1 Billion requests per day.

  • Latency: Critical. The gateway must add minimal overhead, ideally < 20ms per request.

  • Availability: Tier 1 service. 99.99% uptime. If the gateway is down, the whole platform is down.

  • Scalability: Must support horizontal scaling to handle traffic spikes.

  • Consistency: Eventual consistency is acceptable for configuration updates (e.g., a new route might take a minute to propagate to all gateway nodes), but rate limiting counters should be accurate.

Image

4. Back of the envelope estimates

  • Traffic Volume:
    • 1 Billion requests / day.
    • Seconds per day 86,400.
    • Average QPS (Queries Per Second) = 1,000,000,000 / 86,400 12,000 QPS.
    • Peak QPS: Assume 2.5x average 30,000 QPS.
  • Bandwidth:
    • Assume average request size = 2 KB.
    • Throughput = 30,000 QPS x 2 KB = 60 MB/s.
    • This is well within the capacity of standard 1Gbps or 10Gbps network interfaces.
  • Memory for Rate Limiting:
    • Assume we track 10 Million active users/IPs.
    • Each counter needs a Key (User ID) + Value (Integer) + Overhead 100 Bytes.
    • Total Memory = 10M x 100 Bytes = 1 GB.
    • This fits easily into a single Redis instance (though we will cluster it for availability).
Image

5. API design

The Gateway has two interfaces: the Traffic Interface (transparent proxy) and the Admin API (configuration).

We will design the Admin API used by developers.

1. Register Service

  • Method: POST /admin/services
  • Body: { "name": "order-service", "protocol": "http", "host": "order.internal" }
  • Response: 201 Created (returns service_id).

2. Create Route

  • Method: POST /admin/routes
  • Body:
{ "path\_pattern": "/api/v1/orders/\*", "service\_id": "order-service", "auth\_required": true, "rate\_limit\_policy": "standard\_user" }
  • Response: 201 Created (returns route_id).

3. Update Policy

  • Method: PUT /admin/routes/{route_id}/policy
  • Body: { "rate_limit": 100, "window": "60s" }
  • Response: 200 OK.

6. High-level architecture

The core design principle here is the separation of the Control Plane and the Data Plane. This is the standard pattern used by modern gateways like Envoy, Kong, or AWS API Gateway.

1. The Separation of Concerns

In older systems, configuration (routes, users) and traffic handling often lived in the same monolithic application or database. This design decouples them to maximize performance.

  • The Data Plane:
    • What it is: These are the API Gateway nodes (servers) that actually touch the user traffic.

    • State: They are Stateless. They do not store any persistent data on their local hard drives.

    • Memory Usage: They load the entire routing configuration (which URL goes where) into their RAM. This ensures that routing decisions happen in nanoseconds, not milliseconds.

    • Scalability: Because they are stateless, you can scale them horizontally (add more nodes) instantly behind a Load Balancer.

  • The Control Plane:
    • What it is: The administrative side where developers define rules (e.g., "Block IP 1.2.3.4" or "Route /payments to PaymentService").

    • Components: This includes the Admin API, the PostgreSQL Database (Config DB), and the Admin Dashboard.

    • Flow: When a developer changes a setting, they talk to the Control Plane. The Control Plane saves it to the DB and then pushes the update to the Data Plane.

2. The Configuration Sync (Pub/Sub)

The most complex part of this architecture is answering: How do the Gateway nodes know that a new route was added without querying the database every time?

  • The Problem: If 10,000 requests come in per second, we cannot query PostgreSQL 10,000 times to check if a route exists. It would crash the DB.

  • The Solution (Pub/Sub):

    1. Admin updates a route in the Control Plane.
    2. Control Plane publishes a message to a Pub/Sub channel (like Redis Pub/Sub or Kafka).
    3. All Gateway Nodes are subscribed to this channel.
    4. They receive the message ("New Route: /orders") and update their local RAM immediately.
    5. Result: memory lookup for incoming traffic with zero database load.

3. Side-Car Components

  • Redis Cluster: While routing rules are local (RAM), Rate Limiting counters must be global. If User A hits Gateway Node 1 five times, and Gateway Node 2 five times, the total is 10. The nodes must share this count. They use Redis as a shared, high-speed counter storage.
Image

7. Data model

We use a relational database for the Control Plane configuration because the data is structured and read-heavy.

1. Services Table

  • id (PK): UUID
  • name: VARCHAR (e.g., "payment-service")
  • host: VARCHAR
  • timeout_ms: INT

2. Routes Table

  • id (PK): UUID
  • service_id (FK): Links to Services
  • path_pattern: VARCHAR (e.g., /api/payments/*)
  • method: VARCHAR (GET, POST)
  • auth_required: BOOLEAN

3. Policies Table (For rate limits, plugins)

  • id (PK): UUID
  • route_id (FK): Links to Routes
  • type: VARCHAR (e.g., "RATE_LIMIT")
  • config: JSON (e.g., {"limit": 50, "window": "60s"})

Note: Gateway nodes do not query this DB for every request. They hold a copy of this data in their local RAM.

8. Core flows end to end

This section describes the "Life of a Request" using the Middleware Chain pattern.

Imagine the Gateway as a pipeline; the request enters one end and flows through a series of filters (middleware) before reaching the backend.

Flow 1: The Happy Path (Success)

This is what happens when a legitimate user makes a valid request.

  1. Entry & SSL Termination (The Heavy Lifting)

    • Why here? Decrypting HTTPS (TLS) requires significant CPU power. By doing this at the Gateway (Termination), we "offload" this work. The microservices behind the gateway can speak plain HTTP (faster) because they are inside a secure private network.

    • Trace ID: The Gateway generates a UUID (e.g., req-123). This ID is passed to the backend. If the request fails later, you can search logs for req-123 to see the entire path.

  2. Middleware 1: Routing Engine (The Map)

    • The Gateway looks at the URL path (/orders/123).

    • It checks its In-Memory Trie (Prefix Tree) or Hash Map to find a match.

    • Decision: "This belongs to the Order Service."

  3. Middleware 2: Authentication (The Bouncer)

    • Validation: The Gateway checks the Authorization: Bearer <token> header.

    • Stateless Check: It does not call an Auth Service (which adds latency). Instead, it uses a cryptographic Public Key to verify the JWT signature locally.

    • Header Injection: Once verified, the Gateway extracts the User ID (user_99) from the token and injects it as a standard HTTP header (X-User-ID: user_99).

    • Benefit: The backend service doesn't need to know how to parse JWTs; it just trusts the X-User-ID header.

  4. Middleware 3: Rate Limiting (The Traffic Cop)

    • The Gateway constructs a unique key: ratelimit:{user_id}:{endpoint}.

    • It performs an atomic increment in Redis.

    • Check: Is the new value Limit? If yes, proceed.

  5. Middleware 4: Service Discovery (The Phonebook)

    • We know we need the "Order Service," but we don't know its IP address. In dynamic environments (like Kubernetes), IPs change all the time.

    • The Gateway asks the Service Registry (Consul/K8s DNS): "Where is Order Service?"

    • Registry answers: 10.0.5.1:8080.

  6. Forwarding (The Proxy)

    • The Gateway opens a connection to 10.0.5.1, sends the request, waits for the response, and streams it back to the client.
Image

Flow 2: The Blocked Path (Protection)

This demonstrates the "Fail Fast" principle.

  1. Scenario: A bot is spamming the API.

  2. Steps 1-2: SSL and Routing happen as normal.

  3. Step 3 (Rate Limiting): The Gateway checks Redis. Redis says the count is 51 (Limit is 50).

  4. Short Circuit: The Gateway stops execution immediately.

    • It does not do Service Discovery.
    • It does not open a connection to the backend.
    • It returns HTTP 429 Too Many Requests.
    • Benefit: The backend microservice never even knows a request happened. This saves the backend's CPU and Database connections for legitimate users.
Image

9. Caching and read performance

We use caching in two distinct places to ensure speed.

1. Configuration Caching (Critical for Latency)

  • Problem: We cannot read the SQL database for every API call; it's too slow.

  • Solution: Every Gateway node keeps the entire Routing Table in its own RAM.

  • Update: When an admin changes a route, the Control Plane publishes an event via Pub/Sub (e.g., Redis Pub/Sub). All gateway nodes listen to this channel and update their RAM instantly.

2. Response Caching (Optional)

  • Problem: Frequent calls for static data (e.g., "Get list of currencies") waste backend resources.

  • Solution: The Gateway can cache the upstream response in Redis with a TTL (e.g., 5 minutes).

  • Logic: If a request matches a cacheable route, the Gateway checks Redis first. If a hit occurs, it returns data immediately, bypassing the backend.

10. Storage, indexing and media

  • Logs (Elasticsearch/Splunk):
    • The Gateway generates massive logs. We do not write to the local disk. We stream logs to an external aggregator.
    • These logs are the "source of truth" for debugging (e.g., "Why did request X fail?").
  • Metrics (Prometheus):
    • We aggregate counters (2xx_count, 5xx_count) and latency histograms (p99_latency) to monitor health.
  • Media Handling (Large Files):
    • Anti-Pattern: Do not stream 1GB video uploads through the Gateway. It blocks connections and eats bandwidth.
    • Pattern: Use Presigned URLs. The client asks the Gateway for permission to upload. The Gateway returns a signed URL for S3 (Amazon Simple Storage Service).2 The client uploads the file directly to S3, bypassing the Gateway entirely.

11. Scaling strategies

1. Horizontal Scaling (Statelessness)

  • The Gateway nodes hold no user session data (sessions are tokens).
  • We can scale from 5 nodes to 500 nodes by simply launching new instances. The Load Balancer automatically starts sending traffic to them.
  • Auto-scaling: We trigger scaling based on CPU usage (e.g., if CPU > 60%, add nodes).

2. Bulkhead Pattern

  • We can isolate critical traffic.
  • Implementation: Deploy separate Gateway clusters for "Public API" (external users) vs "Partner API" (B2B). If the Public API gets DDoS-ed, the Partner API remains unaffected.

12. Reliability, failure handling and backpressure

1. Circuit Breaker

  • If the Payment Service fails 5 times in a row, the Gateway "trips" the circuit.
  • For the next 30 seconds, it fails all requests to Payment immediately (Fast Fail).
  • Why: This prevents threads from piling up waiting for a dead service and gives the service time to recover.

2. Timeouts

  • Every request to a backend must have a strict timeout (e.g., 5 seconds). Never let a request hang indefinitely.

3. Retry Logic

  • Only retry on "network blips" or 503 errors.
  • Idempotency: Never retry non-idempotent methods like POST /payment automatically, as it might charge the user twice.

13. Security, privacy and abuse

1. Centralized SSL/TLS

  • The Gateway manages certificates. This simplifies the backend services (they can speak plain HTTP inside the private network).

2. Authentication Offloading

  • The Gateway validates tokens. Backend services just trust the X-User-ID header sent by the Gateway. This prevents "forgot to check token" bugs in individual microservices.

3. WAF (Web Application Firewall)

  • We place a WAF (like AWS WAF or Cloudflare) in front of the Gateway to block SQL Injection, XSS, and malicious bot traffic before it even reaches our code.

14. Bottlenecks and next steps

Main Bottlenecks:

  • Redis Latency: Rate limiting requires a network call to Redis for every request. At massive scale, this adds up.
    • Fix: Use Local Token Buckets (in-memory rate limiting) for high-volume users, syncing with Redis asynchronously.
  • Configuration Sync: As we grow to 1000+ nodes, ensuring all nodes update their config instantly is hard.
    • Fix: Use a dedicated control plane protocol (like xDS in Envoy) for robust config synchronization.

Summary

  • We designed a High Availability Gateway using stateless nodes and horizontal scaling.

  • We separated Control Plane (Config) from Data Plane (Traffic) for stability.

  • We detailed a Middleware Chain flow to handle Auth, Routing, and Rate Limiting step-by-step.

  • We optimized performance by caching configuration in RAM to ensure <20ms latency.

Design a Code Deployment System
Design Amazon Lambda
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High-level architecture

7. Data model

8. Core flows end to end

Flow 1: The Happy Path (Success)

Flow 2: The Blocked Path (Protection)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary